// 导入axios
import axios from 'axios'
// 
const host = 'http://127.0.0.1:4000'
// 定义host前缀
// const host = 'http://localhost:4000'

// 创建axios实例
const http = axios.create({
    baseURL: host,
    timeout: 5000,
    headers: {
        token: localStorage.getItem('token')
    }
})

// 封装axios请求
// get请求
const get = (url:string, data={}) => {
    return http.get( `${host}${url}`,
        {params: data, 
            headers: {
                token: localStorage.getItem('token')
            }
        }
    )
    .then(res =>res.data)
   .catch(err => {
        console.log(err)
    })
}
    
// post请求
const post = (url:string, data={}) => {
    return http.post( `${host}${url}`,
        data,
        {headers: {
            "Content-Type":"application/x-www-form-urlencoded",
            token: localStorage.getItem('token')
        }}
    )
   .then(res =>res.data)
   .catch(err => {
        console.log(err)
    })
}
// 图片上传
const upload = (url:string, data={}) => {
    return http.post( `${host}${url}`,
        data,
        {headers: {
            "Content-Type":"multipart/form-data",
            token: localStorage.getItem('token')
        }}
    )
   .then(res =>res.data)
   .catch(err => {
        console.log(err)
    })
}

// 导出请求方法
export default {
    host,
    get,
    post,
    upload
}


